import { ref, reactive } from 'vue'
import { addImageClass, getImageClass, updateImageClass } from '@/api/http'
import { toast } from '@/composables/util'
// 新增
export const useAddImg1 = (app = {}) => {
  const formDrawerRef = ref(null)
  const ruleFormRef = ref(null)

  const ImageCategoryList = ref([])
  const total = ref(0)
  const activeId = ref(0)

  const form = reactive({
    name: '',
    order: '',
  })

  const rules = reactive({
    name: {
      required: true,
    },
    order: {
      required: true,
    },
  })

  // const emit = defineEmits(["change"])
  const changeActive = (item) => {
    activeId.value = item.id
    app.emit('change', item.id)
    // emit('change', id)
  }
  const getLeftList = async (page) => {
    let { data } = await getImageClass({ page })
    ImageCategoryList.value = data.list
    total.value = data.totalCount
    activeId.value = ImageCategoryList.value.id
    let item = ImageCategoryList.value[0]
    if (item) {
      changeActive(item)
    }

  }
  const addImg = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        formDrawerRef.value.showLoading(true)


        const fn = app.editId ? updateImageClass(app.editId, form) : addImageClass(form)
        fn.then(res => {

          toast('操作成功！')
          getLeftList(1)
          formDrawerRef.value.showLoading(false)
          formDrawerRef.value.showDrawer(false)
        })

      } else {
        console.log('error submit!', fields)
      }
    })
  }

  getLeftList(1)
  return {
    rules,
    formDrawerRef,
    ruleFormRef,
    form,
    ImageCategoryList,
    activeId, total,
    getLeftList, addImg, changeActive
  }
}

